﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using DC2010.Objects.Common;
using DC2010.Objects.Info;
using DC2010.Objects.Base;

namespace DC2010.Objects
{
	[Serializable]
    public class Layer : BaseObject, ICloneable
    {
	    /// <summary>
        /// Id of objects
		/// Key is combination of X and Y -> on position X=13,Y=15 gives us key: "13,15"
		/// Value is id of referenced object. We should know what kind of object is referenced
		/// based on layer. For example on "tile layer" there will be references to "TileSystem" :)
        /// </summary>		
		public List<KeyValue> tableOfObjects {get; set;}

        /// <summary>
        /// Experience multiplier for current layer.
        /// </summary>
        public int ExperienceMultiplier { get; set; }

	
		[XmlIgnore]
		public BaseObject this[int X, int Y]
		{
			get
			{
				string key = X+"_"+Y;
				KeyValue x = (from i in tableOfObjects
					     where i.Key == key
						 select i).FirstOrDefault();

                if (x != null)
                {
                    ObjectReference refer = new ObjectReference();
                    refer.ObjectType = BaseObjectType.Tile;
                    refer.ReferencedId = x.Value;
                    BaseObject bo = Root.I.GameSystem.GetReferencedObject(refer);

                    return bo;
                }
			    return null;
			}
		}		

        public Layer(BaseObjectType objectType)
            : base()
        {
            Type = objectType;
            tableOfObjects = new List<KeyValue>();
        }

        public Layer()
        {
            tableOfObjects = new List<KeyValue>();
        }

        public void ClearXY(int X, int Y)
        {
            string s = X + "_" + Y;

            var x = (from i in tableOfObjects
                     where i.Key == s
                     select i).ToList();

            foreach (KeyValue keyValue in x)
            {
                tableOfObjects.Remove(keyValue);
            }
        }

        public object Clone()
        {
            Layer l = (Layer)this.MemberwiseClone();
            l.tableOfObjects = new List<KeyValue>();

            foreach (KeyValue kv in tableOfObjects)
            {
                KeyValue  kvNew = new KeyValue();
                kvNew.Key = kv.Key;
                kvNew.Value = kv.Value;

                l.tableOfObjects.Add(kvNew);
            }

            return l;
        }
    }
}
